<template>
  <div class="app-container">
    <!--    <el-row :gutter="20">-->
    <!-- 设备列表 -->
    <!--      <el-col :lg="24" :xs="24">-->
    <div class="toolbar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="场地名称/编号"
            clearable
            style="width: 300px;height: 30px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status" >
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            class="!w-[200px]"
            style='width: 200px;height: 30px'
          >
            <el-option
              v-for="item in equipmentStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size='large' @click="handleQuery" :icon='Search'
          >搜索</el-button
          >
          <el-button @click="resetQuery" size='large' :icon='Refresh'>
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="toolbar" style='margin-bottom: 10px;'>
      <div>
        <el-button
          size='large'
          type="primary"
          :icon='Plus'
          @click="openDialog('user-form')"
        >新增</el-button
        >
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="pageData"
      :strip='true'
      :border='true'
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        key="id"
        label="场地id"
        align="center"
        prop="id"
        width="100"
      />
      <el-table-column
        key="sn"
        label="场地编号"
        align="center"
        prop="sn"
        width="200"
      />
      <el-table-column
        label="场地名称"
        width="200"
        align="center"
        prop="name"
      />
      <el-table-column
        label="月租金"
        width="200"
        align="center"
        prop="rent"
      />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status == 3 ? 'success' : 'info'">{{
              scope.row.status == 0 ? "未使用" : (scope.row.status == 1 ? "使用中" : (scope.row.status == 2 ? "维护中" : "已到期"))
            }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="地址"
        align="center"
        prop="address"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            type="success"
            size="large"
            @click="openDialog('user-form', scope.row.id)"
            :icon="Edit"
          >编辑</el-button
          >
          <el-button
            type="warning"
            size="large"
            @click="handleDeleteEquipment(scope.row.id)"
            :icon="Delete"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-footer class='footer'>
      <el-pagination
        large
        background
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-count='pagination.pageCount'
        layout='total, prev, pager, next'
        :total='pagination.total'
        class='mt-4'
        style='float: right'
        @change='getPage'
      />
    </el-footer>
    <!--        </el-card>-->
    <!--      </el-col>-->
    <!--    </el-row>-->

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 用户新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'user-form'"
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="场地编号" prop="sn">
          <el-input
            v-model="formData.sn"
            :disabled="!!formData.id"
            placeholder="请输入场地型号"
          />
        </el-form-item>

        <el-form-item label="场地名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入场地名称" />
        </el-form-item>
        <el-form-item label="月租金" prop="rent">
          <el-input type="number" v-model="formData.rent" placeholder="请输入月租金" />
        </el-form-item>
<!--        <el-form-item label="设备价格" prop="price">
          <el-input v-model="formData.price" placeholder="请输入设备价格，单位为分" />
        </el-form-item>-->
        <el-form-item label="场地状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择">
            <el-option
              v-for="item in equipmentStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input
            type="textarea"
            autosize
            clearable
            v-model="formData.address"
            placeholder="请填写备注"
          />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import {
  getVenuePage,
  getVenueForm,
  addVenue,
  updateVenue,
  deleteVenue
} from "@/api/resource/venue";
import { Plus, Delete, Edit, Search, Share, Refresh } from '@element-plus/icons-vue'
import type { Venue, VenueForm, VenueQueryParams, VenueVO } from '@/api/resource/venue/types.ts'
import { type UploadInstance, ElMessageBox, ElMessage, ElForm } from 'element-plus'
import { ref,onMounted,reactive } from "vue";

const queryFormRef = ref(ElForm); // 查询表单
const userFormRef = ref(ElForm); // 用户表单
const uploadRef = ref<UploadInstance>(); // 上传组件

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除用户ID集合 用于批量删除
const queryParams = reactive<VenueQueryParams>({
  pageNum: 1,
  pageSize: 10,
});
const total = ref(0); // 数据总数
const pageData = ref<VenueVO[]>(); // 分页数据
const pagination = ref({
  currentPage: 1,pageSize: 10,total: 0,pageCount: 1
});
// watch(dateTimeRange, (newVal) => {
//   if (newVal) {
//     queryParams.startTime = newVal[0];
//     queryParams.endTime = newVal[1];
//   }
// });

const disabled = ref(false);

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 800,
  title: "",
});

const equipmentStatusOptions = [{
  value: 0,
  label: '未使用'
},{
  value: 1,
  label: '使用中'
},{
  value: 2,
  label: '维护中'
},{
  value: 3,
  label: '已损坏'
}]

// 用户表单数据
const formData = reactive<VenueForm>({
  status: undefined,
});

// 用户导入数据
const importData = reactive({
  deptId: undefined,
  file: undefined,
  fileList: [],
});

// 校验规则
const rules = reactive({
  name: [{ required: true, message: "场地名不能为空", trigger: "blur" }],
  sn: [{ required: true, message: "场地编号不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  getPage(queryParams.pageNum,queryParams.pageSize);
}

function getPage(currentPage:number,pageSize :number){
  pagination.value.currentPage = queryParams.pageNum = currentPage || 1;
  pagination.value.pageSize = queryParams.pageSize = pageSize || 10
  loading.value = true;
  getVenuePage(queryParams)
    .then(({ data }) => {
      pageData.value = data.records;
      total.value = data.total;
      pagination.value.currentPage = data.current
      pagination.value.pageSize = data.size
      pagination.value.total = data.total
      pagination.value.pageCount = data.pages
      queryParams.pageNum = data.current;
      queryParams.pageSize = data.size;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 * @param id 用户ID
 */
async function openDialog(type: string, id?: number) {
  dialog.visible = true;
  dialog.type = type;

  if (dialog.type === "user-form") {
    if (id) {
      dialog.title = "修改场地信息";
      disabled.value = true;
      getVenueForm(id).then(({ data }) => {
        Object.assign(formData, { ...data });
      });
    } else {
      dialog.title = "新增场地信息";
    }
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  用户表单：user-form
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();

    formData.id = undefined;
    // formData.status = 1;
  }
}

/** 表单提交 */
const handleSubmit = (() => {
  if (dialog.type === "user-form") {
    userFormRef.value.validate((valid: any) => {
      if (valid) {
        const id = formData.id;
        console.log('==========================',formData);
        loading.value = true;
        if (id) {
          updateVenue(formData)
            .then(() => {
              ElMessage.success("修改场地信息成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          addVenue(formData)
            .then(() => {
              ElMessage.success("新增场地信息成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
});

/** 删除设备 */
function handleDeleteEquipment(id: number) {
  ElMessageBox.confirm("确认删除场地信息?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteVenue(id).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

onMounted(() => {
  handleQuery();
});
</script>
.toolbar {
padding: 10px 0;
}
<style scoped>
.footer {
  margin-top: 20px;
}
</style>
